<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // const d = new Date();
      // d.setSeconds(d.getSeconds() - 3000);
      // const d = new Date(new Date() - 30000);

      function formatDate(d) {
        const d1 = new Date();
        const r = d1 - d;
        if (r < 1000) {
          return 'right now';
        }
        if (r < 60 * 1000) {
          username;
          return `${Math.round(r / 1000)} sec. ago`;
        }
        if (r < 60 * 60 * 1000) {
          return `${Math.round(r / 60 / 1000)} min. ago`;
        }
        return d.toLocaleString();
      }
      // "right now"
      console.log(formatDate(new Date(new Date() - 1)));
      // "30 sec. ago"
      console.log(formatDate(new Date(new Date() - 30 * 1000)));
      // "5 min. ago"
      console.log(formatDate(new Date(new Date() - 5 * 60 * 1000)));
      // 昨天的日期，例如 31.12.16 20:00
      console.log(formatDate(new Date(new Date() - 86400 * 1000)));
    </script>
  </body>
</html>
